//
//  GSNetworkManager.m
//  GameSky
//
//  Created by lanou on 16/1/10.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSNetworkManager.h"

@implementation GSNetworkManager

+ (void)requestWithUrlStr:(NSString *)urlStr paraDict:(NSDictionary *)paraDict method:(RequestType)method success:(void (^)(NSData *data))success failure:(void (^)(NSError *error))failure {
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        if (!paraDict.count) {
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in paraDict) {
                NSString *str = [NSString stringWithFormat:@"%@=%@", key, paraDict[key]];
                [strArray addObject:str];
            }
            // 用'&'把数组元素依次连接起来;
            NSString *paraString = [strArray componentsJoinedByString:@"&"];
            [request setHTTPBody:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            // 请求成功
            success(data);
        } else {
            // 请求失败
            failure(error);
        }
    }];
    [task resume];
}

@end
